package com.demo.youxuanmall.service.impl;

import com.demo.youxuanmall.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.upload.avatar.path}")
    private String avatarPath;

    @Override
    public String uploadAvatar(MultipartFile file) {
        try {
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || (!contentType.startsWith("image/jpeg") && !contentType.startsWith("image/png"))) {
                throw new IllegalArgumentException("只支持jpg、png格式的图片");
            }

            // 检查文件大小（2MB）
            if (file.getSize() > 2 * 1024 * 1024) {
                throw new IllegalArgumentException("图片大小不能超过2MB");
            }

            // 确保目录存在
            Path avatarDir = Paths.get(uploadPath, avatarPath);
            if (!Files.exists(avatarDir)) {
                Files.createDirectories(avatarDir);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null ? 
                originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path targetPath = avatarDir.resolve(filename);
            try {
                Files.copy(file.getInputStream(), targetPath);
            } catch (IOException e) {
                log.error("保存文件失败", e);
                throw new RuntimeException("保存文件失败：" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    log.warn("关闭文件流失败", e);
                }
            }

            // 返回相对路径
            return "/upload/avatars/" + filename;
        } catch (IOException e) {
            log.error("上传头像失败", e);
            throw new RuntimeException("上传头像失败：" + e.getMessage());
        }
    }

    @Override
    public void deleteFile(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return;
        }

        try {
            // 从URL路径转换为文件系统路径
            String relativePath = filePath.replace("/upload/", "");
            Path path = Paths.get(uploadPath, relativePath);
            if (Files.exists(path)) {
                Files.delete(path);
                log.info("成功删除文件: {}", filePath);
            }
        } catch (IOException e) {
            log.error("删除文件失败: {}", filePath, e);
        }
    }
} 